/*
 * 创建日期 2006-6-22
 */
package com.jmcgg.freesky.common.util;

import java.io.FileWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * Title: FreeSky Common Java Library <br>
 * Description: FreeSky Common Java Library <br>
 * Copyright: Copyright (c) 2005~2009 www.afss.cn <br>
 * Company: Amei's FreeSky Studio <br>
 * 
 * @author <b>Jacky Chou</b> (AFSS [Amei's FreeSky Studio])
 * @version 1.2.1, 2008-08-05, Clean and optimize the source code.<br>
 *          1.2.0, 2008-02-23, Upgrade freesky.jar to 1.2.0 with Struts 2<br>
 *          1.0.0, 2006-05-30, Initial Version
 */
public class XMLUtil extends FreeskyUtil {
	/**
	 * Log4J Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(XMLUtil.class);

	/**
	 * Return a Document object which points to the input xml file
	 * 
	 * @param xmlfile
	 * @return
	 */
	public static Document getXMLDoc(String xmlfile) {
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document doc = builder.parse(xmlfile);
			return doc;
		} catch (Exception e) {
			logger.error(
					"An error occurred in getXMLDoc() : " + e.getMessage(), e);
			return null;
		}
	}

	/**
	 * Return the Node with the specific name under the parent node
	 * 
	 * @param parent
	 * @param name
	 * @return
	 */
	public static Node getChild(Node parent, String name) {
		NodeList children = parent.getChildNodes();
		int len = children.getLength();
		Node node = null;
		for (int i = 0; i < len; i++) {
			node = children.item(i);
			String thisname = node.getNodeName();
			if (name.equals(thisname)) {
				return node;
			}
		}
		return null;
	}

	/**
	 * Return the text of the Node
	 * 
	 * @param node
	 * @return
	 */
	public static String getTextValue(Node node) {
		if ((node.getNodeType() == Node.TEXT_NODE)
				|| (node.getNodeType() == Node.CDATA_SECTION_NODE)) {
			return node.getNodeValue();
		} else {
			return null;
		}
	}

	public static void setTextValue(Document xmldoc, Node node, String value) {
		if ((node.getNodeType() == Node.TEXT_NODE)
				|| (node.getNodeType() == Node.CDATA_SECTION_NODE)) {
			try {
				TransformerFactory tf = TransformerFactory.newInstance();
				Transformer tr = tf.newTransformer();
				tr.setOutputProperty(" encoding ", " GBK ");
				node.setNodeValue(value);
				DOMSource ds = new DOMSource(xmldoc);
				StreamResult sr = new StreamResult(new FileWriter(" test.xml "));
				tr.transform(ds, sr);
			} catch (Exception e) {
				if (logger.isDebugEnabled()) {
					logger.debug(" SCXMLUtils:  " + e);
				}
			}
		} else {
			if (logger.isDebugEnabled()) {
				logger.debug(" SCXMLUtils: This node is not a text! ");
			}
		}
	}

	public static void main(String[] args) {
		String nodevalue = null;
		Document xmldoc = XMLUtil.getXMLDoc(" test.xml ");
		if (xmldoc == null) {
			if (logger.isDebugEnabled()) {
				logger.debug(" Create XML Document failed! ");
			}
			return;
		}
		Element root = xmldoc.getDocumentElement();
		if (root == null) {
			if (logger.isDebugEnabled()) {
				logger.debug(" Get root of XML Document failed! ");
			}
			return;
		}
		Node node1 = XMLUtil.getChild(root, " Master ");
		if (node1 == null) {
			if (logger.isDebugEnabled()) {
				logger.debug(" Get node failed! ");
			}
			return;
		}
		nodevalue = XMLUtil.getTextValue(node1.getFirstChild());
		if (nodevalue == null) {
			if (logger.isDebugEnabled()) {
				logger.debug(" Get value of node failed! ");
			}
			return;
		}
		if (logger.isDebugEnabled()) {
			logger.debug(" The Master is  " + nodevalue.trim());
		}
	}
}
